import os, sys
import vtk

def readUnstructuredGrid(filename):
    # 创建一个vtkUnstructuredGridReader实例
    reader = vtk.vtkUnstructuredGridReader()
    reader.SetFileName(filename)
    reader.Update()  # 更新读取器以读取数据
    return reader.GetOutput()

def unstructuredGridToPolyData(unstructuredGrid):
    # 创建一个vtkGeometryFilter实例
    geometryFilter = vtk.vtkGeometryFilter()
    geometryFilter.SetInputData(unstructuredGrid)
    geometryFilter.Update()  # 更新过滤器以执行转换
    return geometryFilter.GetOutput()

def writePolyData(polyData, filename):
    # 创建一个vtkXMLPolyDataWriter实例
    writer = vtk.vtkXMLPolyDataWriter()
    writer.SetFileName(filename)
    writer.SetInputData(polyData)
    writer.Write()

def vtk2vtp(vtkfile,vtpfile):
    # 读取unstructuredGrid文件数据
    unstructuredGrid = readUnstructuredGrid(vtkfile)
    # 将unstructuredGrid转换为polyData
    polyData = unstructuredGridToPolyData(unstructuredGrid)
    # 将polyData写入vtp格式文件
    writePolyData(polyData, vtpfile)

if __name__ == "__main__":
    args = sys.argv
    binary = False
    if '-b' in args:
        args.remove('-b')
        binary = True
    if len(args) < 2:
        print('Batch converts vtk files to vtp files.\nUsage:\n    vtk2vtp.py model1.vtk model2.vtk ...')
        print('    [-b] causes output to be in binary format, much smaller vtp file size, if it happens to work')
        sys.exit()
    infiles = args[1:]
    for vtkfile in infiles:
        if vtkfile[-4:] != '.vtk':
            print(vtkfile +" doesn't look like a vtk file, won't convert")
            continue
        vtk2vtp(vtkfile, vtkfile[:-4]+'.vtp')